package cn.safekeeper.guide.admin.utils;

import cn.safekeeper.guide.admin.constant.Constants;
import cn.safekeeper.guide.admin.domain.entity.SysLoginInfo;
import cn.safekeeper.guide.admin.service.ISysLoginInfoService;
import cn.safekeeper.guide.admin.utils.ip.AddressUtils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * 异步日志记录
 */
@Component
public class AsyncLogUtil {
    private static Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    private static ThreadPoolExecutor exe;

    static {
        int poolSize = Runtime.getRuntime().availableProcessors();
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-MqttPushUtil-%d").build();
        exe = new ThreadPoolExecutor(1, poolSize, 60L, TimeUnit.SECONDS, workQueue, namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    public void recordLoginInfoAsync(String username, String status, String message,
                                     String ip, String os,String browser, Object... args) {
        exe.execute(() -> this.recordLoginInfo(username, status, message, ip, os, browser,args));
    }

    /**
     * 记录登录信息
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息
     * @param args     列表
     * @return 任务task
     */
    private void recordLoginInfo(String username, String status, String message,
                                 String ip, String os,String browser, Object... args) {
        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(LogUtils.getBlock(ip));
        s.append(address);
        s.append(LogUtils.getBlock(username));
        s.append(LogUtils.getBlock(status));
        s.append(LogUtils.getBlock(message));
        // 打印信息到日志
        sys_user_logger.info(s.toString(), args);
        // 封装对象
        SysLoginInfo sysLoginInfo = new SysLoginInfo();
        sysLoginInfo.setUserName(username);
        sysLoginInfo.setIpaddr(ip);
        sysLoginInfo.setLoginLocation(address);
        sysLoginInfo.setBrowser(browser);
        sysLoginInfo.setOs(os);
        sysLoginInfo.setMsg(message);
        // 日志状态
        if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            sysLoginInfo.setStatus(Constants.SUCCESS);
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            sysLoginInfo.setStatus(Constants.FAIL);
        }
        // 插入数据
        SpringUtils.getBean(ISysLoginInfoService.class).insertLogininfor(sysLoginInfo);
    }
}
